<?php
/**
 * Created by PhpStorm.
 * User: DaXiong
 * Date: 2018/11/18
 * Time: 11:12
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\User as Users;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\DB;


class AuthController extends Controller
{
    //注册
    public function reg(){
        return 'reg';
    }

    //登录
    public function login(){
        $code = (string)request('code','');
        $app = app('wechat.mini_program');
        $data = $app->auth->session($code); //""081tAsH1149ipP1IqQH11PRxH11tAsHO""
        if(!isset($data['openid'])){
            return $this->returnJson(1, '登录失败',$data);
        }
        $user = Users::where('openid',$data['openid'])->first();
        if(!$user){
            //不存在创建新用户
            $user = Users::create([
                'openid' => $data['openid'],
                'password' => bcrypt($data['openid']),
                'register_at' => Carbon::now(),
                'login_at' => Carbon::now(),
            ]);
        }
        if (auth()->attempt(['openid' => $data['openid'], 'password' => $data['openid']])) {
            //删除用户已存在的个人token
            DB::table('oauth_access_tokens')
                ->where('user_id',$user['id'])
                ->delete();
            $return['token'] = $user->createToken('localhost client')->accessToken;
            $return['user']  = $user->toArray();
            return $this->returnJson(0,'',$return);
        }
        return $this->returnJson(1, '登录失败');
    }

    /**
     * 刷新token
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function reToken(){
        try {
            $refreshToken = request('refresh_token','');
            if(empty($refreshToken)){
                return $this->returnJson(1, '参数错误');
            }
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.refresh'), [
                'refresh_token' => $refreshToken,
            ]);
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (RequestException $exception) {
            return $this->returnJson(1, '刷新失败');
        }
    }

    //退出登录
    public function logout(){
        return 'logout';
    }
}